#define  _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
#include<limits.h>
#include<stdlib.h>

int cmp(void* s1, void* s2)
{
    return *(int*)s1 - *(int*)s2;
}

int threeSumClosest(int* nums, int numsSize, int target)
{
    int sum = 10000000;
    qsort(nums, numsSize, sizeof(int), cmp);
    int i = 0;

    for (i = 0; i < numsSize - 2; i++)
    {
        int left = i + 1;
        int right = numsSize - 1;
        if (i > 0 && nums[i] == nums[i - 1])
            continue;
        while (left < right)
        {
            if (abs(nums[i] + nums[right] + nums[left] - target) < abs(sum - target))
            {
                sum = nums[i] + nums[right] + nums[left];
            }
            if (nums[i] + nums[right] + nums[left] > target)
            {
                right--;
            }
            else if (nums[i] + nums[right] + nums[left] < target)
            {
                left++;
            }
            else
            {
                return target;
            }
        }

    }
    return sum;
}
int main()
{
    int arr[] = { 1,2,3,8,7 };
    int ret = threeSumClosest(arr,5,10);
    printf("%d\n", ret);
	return 0;
}